package org.jeecg.modules.online.auth.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.online.auth.entity.OnlAuthData;
import org.jeecg.modules.online.auth.entity.OnlAuthPage;
import org.jeecg.modules.online.auth.entity.OnlAuthRelation;
import org.jeecg.modules.online.auth.service.IOnlAuthDataService;
import org.jeecg.modules.online.auth.service.IOnlAuthPageService;
import org.jeecg.modules.online.auth.service.IOnlAuthRelationService;
import org.jeecg.modules.online.auth.util.AuthConstants;
import org.jeecg.modules.online.auth.vo.AuthColumnVO;
import org.jeecg.modules.online.auth.vo.AuthPageVO;
import org.jeecg.modules.online.cgform.entity.OnlCgformButton;
import org.jeecg.modules.online.cgform.entity.OnlCgformField;
import org.jeecg.modules.online.cgform.entity.OnlCgformHead;
import org.jeecg.modules.online.cgform.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Title: Controller
 * @Description: Online表单开发
 * @Author: jeecg-boot
 * @Date: 2019-03-12
 * @Version: V1.0
 */
@Slf4j
@RestController("onlCgformAuthController")
@RequestMapping("/online/cgform/api")
public class OnlCgformAuthController {

	@Autowired
	private IOnlCgformFieldService onlCgformFieldService;

	@Autowired
    private IOnlAuthDataService onlAuthDataService;

	@Autowired
	private IOnlAuthPageService onlAuthPageService;

	@Autowired
	private IOnlCgformButtonService onlCgformButtonService;

	@Autowired
	private IOnlAuthRelationService onlAuthRelationService;
	@Autowired
	private IOnlCgformHeadService onlCgformHeadService;
    /* ---------------------------------------数据权限维护-begin-------------------------------------- */

	/**
	 * 根据cgformId查询所有的数据权限配置
	 * @param cgformId
	 * @return
	 */
	@GetMapping(value = "/authData/{cgformId}")
	public Result<List<OnlAuthData>> authDataList(@PathVariable("cgformId") String cgformId){
		Result<List<OnlAuthData>> result = new Result<>();
		LambdaQueryWrapper<OnlAuthData> query = new LambdaQueryWrapper<OnlAuthData>();
		query.eq(OnlAuthData::getCgformId, cgformId);
		List<OnlAuthData> ls = this.onlAuthDataService.list(query);
		result.setResult(ls);
		result.setSuccess(true);
		return result;
	}

	/**
	 * 添加
	 * @param onlAuthData
	 * @return
	 */
	@PostMapping(value = "/authData")
	@CacheEvict(value = {CacheConstant.ONLINE_LIST, CacheConstant.ONLINE_FORM}, allEntries = true, beforeInvocation=true)
	public Result<OnlAuthData> addAuthData(@RequestBody OnlAuthData onlAuthData) {
		Result<OnlAuthData> result = new Result<OnlAuthData>();
		try {
			onlAuthDataService.save(onlAuthData);
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.error500("操作失败");
		}
		return result;
	}

	/**
	 * 编辑
	 * @param onlAuthData
	 * @return
	 */
	@PutMapping(value = "/authData")
	@CacheEvict(value = {CacheConstant.ONLINE_LIST, CacheConstant.ONLINE_FORM}, allEntries = true, beforeInvocation=true)
	public Result<OnlAuthData> editAuthData(@RequestBody OnlAuthData onlAuthData) {
		Result<OnlAuthData> result = new Result<OnlAuthData>();
		onlAuthDataService.updateById(onlAuthData);
		result.success("编辑成功！");
		return result;
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/authData/{id}")
	@CacheEvict(value = {CacheConstant.ONLINE_LIST, CacheConstant.ONLINE_FORM}, allEntries = true, beforeInvocation=true)
	public Result<?> deleteAuthData(@PathVariable("id") String id) {
		onlAuthDataService.deleteOne(id);
		return Result.ok("删除成功!");
	}

	/* ---------------------------------------数据权限维护-end-------------------------------------- */




	/* ---------------------------------------按钮权限维护-begin-------------------------------------- */

	/**
	 * 根据cgformId查询所有的数据权限配置
	 * @param cgformId
	 * @return
	 */
	@GetMapping(value = "/authButton/{cgformId}")
	public Result<Map<String,Object>> authButtonList(@PathVariable("cgformId") String cgformId){
		Result<Map<String,Object>> result = new Result<>();
		//查询出所有自定义按钮
		LambdaQueryWrapper<OnlCgformButton> buttonQuery = new LambdaQueryWrapper<OnlCgformButton>()
				.eq(OnlCgformButton::getCgformHeadId,cgformId)
				.eq(OnlCgformButton::getButtonStatus,AuthConstants.BUTTON_VALID)
				.select(OnlCgformButton::getButtonCode,OnlCgformButton::getButtonName,OnlCgformButton::getButtonStyle);
		List<OnlCgformButton> buttonList = onlCgformButtonService.list(buttonQuery);

		//查询 type=2 的按钮权限数据
		LambdaQueryWrapper<OnlAuthPage> query = new LambdaQueryWrapper<OnlAuthPage>()
				.eq(OnlAuthPage::getCgformId,cgformId)
				.eq(OnlAuthPage::getType,AuthConstants.BUTTON);
		List<OnlAuthPage> authList = this.onlAuthPageService.list(query);

		Map<String,Object> map = new HashMap<String,Object>();
		map.put("buttonList",buttonList);
		map.put("authList",authList);
		result.setResult(map);
		result.setSuccess(true);
		return result;
	}

	/**
	 * 按钮启用 逻辑如下
	 * 1.判断是否存在此按钮的权限数据 如果有那么启用的话 就是修改状态为1
	 * 2。如果没有 那么启用就是新增数据 并且状态为1
	 * @param onlAuthPage
	 * @return
	 */
	@PostMapping(value = "/authButton")
	@CacheEvict(value = {CacheConstant.ONLINE_LIST, CacheConstant.ONLINE_FORM}, allEntries = true, beforeInvocation=true)
	public Result<OnlAuthPage> enableAuthButton(@RequestBody OnlAuthPage onlAuthPage) {
		Result<OnlAuthPage> result = new Result<OnlAuthPage>();
		try {
			String id = onlAuthPage.getId();
			boolean exist = false;
			if(oConvertUtils.isNotEmpty(id)){
				OnlAuthPage meta = onlAuthPageService.getById(id);
				if(meta!=null){
					exist = true;
					meta.setStatus(AuthConstants.VALID);
					onlAuthPageService.updateById(meta);
				}
			}
			if(!exist){
				onlAuthPage.setStatus(AuthConstants.VALID);
				onlAuthPageService.save(onlAuthPage);
			}
			result.setResult(onlAuthPage);
			result.success("操作成功！");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.error500("操作失败");
		}
		return result;
	}

	/**
	 * 取消启用
	 * @param id
	 * @return
	 */
	@PutMapping(value = "/authButton/{id}")
	@CacheEvict(value = {CacheConstant.ONLINE_LIST, CacheConstant.ONLINE_FORM}, allEntries = true, beforeInvocation=true)
	public Result<?> editAuthButton(@PathVariable("id") String id) {
		LambdaUpdateWrapper<OnlAuthPage> updateWrapper = new UpdateWrapper<OnlAuthPage>()
				.lambda()
				.eq(OnlAuthPage::getId, id)
				.set(OnlAuthPage::getStatus, AuthConstants.CANCLE);
		onlAuthPageService.update(updateWrapper);
		return Result.ok("操作成功");
	}

	/* ---------------------------------------按钮权限维护-end-------------------------------------- */


	/* ---------------------------------------字段权限维护-begin-------------------------------------- */
	@GetMapping(value = "/authColumn/{cgformId}")
	public Result<List<AuthColumnVO>> authColumnList(@PathVariable("cgformId") String cgformId) {
		Result<List<AuthColumnVO>> result = new Result<>();
		LambdaQueryWrapper<OnlCgformField> query = new LambdaQueryWrapper<OnlCgformField>();
		query.eq(OnlCgformField::getCgformHeadId,cgformId);
		query.orderByAsc(OnlCgformField::getOrderNum);
		List<OnlCgformField> fieldList = this.onlCgformFieldService.list(query);
		if(fieldList==null || fieldList.size()==0) {
			Result.error("未找到对应字段信息!");
		}
		//查询 type=1 的字段权限数据
		LambdaQueryWrapper<OnlAuthPage> query2 = new LambdaQueryWrapper<OnlAuthPage>()
				.eq(OnlAuthPage::getCgformId,cgformId)
				.eq(OnlAuthPage::getType, AuthConstants.COLUMN);
		List<OnlAuthPage> authList = this.onlAuthPageService.list(query2);

		List<AuthColumnVO> ls = new ArrayList<>();
		for(OnlCgformField field: fieldList){
			AuthColumnVO vo = new AuthColumnVO(field);
			Integer status = 0;
			boolean listShow = false, formshow = false, formEdit = false;
			// 需要设置 表单/列表 控制状态
			for(int i=0;i<authList.size();i++){
				OnlAuthPage temp = authList.get(i);

				if(field.getDbFieldName().equals(temp.getCode())){
					status = temp.getStatus();
					if(temp.getPage() == AuthConstants.LIST && temp.getControl() == AuthConstants.SHOW){
						//列表3 可见5
						listShow = true;
					}
					if(temp.getPage() == AuthConstants.FORM){
						//表单5
						if(temp.getControl()==AuthConstants.SHOW){
							//可见5
							formshow = true;
						}else if(temp.getControl()==AuthConstants.EDIT){
							//可编辑3
							formEdit = true;
						}
					}
				}
			}
			vo.setStatus(status);
			vo.setListShow(listShow);
			vo.setFormShow(formshow);
			vo.setFormEditable(formEdit);
			ls.add(vo);
		}
		result.setResult(ls);
		result.ok("加载字段权限数据完成");
		return result;
	}

	/**
	 * 字段启用/置灰
	 * @param authColumnVO
	 * @return
	 */
	@PutMapping(value = "/authColumn")
	@CacheEvict(value = {CacheConstant.ONLINE_LIST, CacheConstant.ONLINE_FORM}, allEntries = true, beforeInvocation=true)
	public Result<?> updateAuthColumn(@RequestBody AuthColumnVO authColumnVO) {
		Result<?> result = new Result<>();
		try {
			if(authColumnVO.getStatus()==AuthConstants.VALID){
				//启用
				this.onlAuthPageService.enableAuthColumn(authColumnVO);
			}else{
				//置灰
				this.onlAuthPageService.disableAuthColumn(authColumnVO);
			}
			result.success("操作成功！");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.error500("操作失败");
		}
		return result;
	}

	/**
	 * 切换 前端点击checkbox时调用
	 * @param authColumnVO
	 * @return
	 */
	@PostMapping(value = "/authColumn")
	@CacheEvict(value = {CacheConstant.ONLINE_LIST, CacheConstant.ONLINE_FORM}, allEntries = true, beforeInvocation=true)
	public Result<?> switchAuthColumn(@RequestBody AuthColumnVO authColumnVO) {
		Result<?> result = new Result<>();
		try {
			this.onlAuthPageService.switchAuthColumn(authColumnVO);
			result.success("操作成功！");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.error500("操作失败");
		}
		return result;
	}

	/* ---------------------------------------字段权限维护-end-------------------------------------- */


	/**
	 * online 字段/按钮 权限数据查询
	 * @param cgformId
	 * @param type
	 * @return
	 */
	@GetMapping(value = "/authPage/{cgformId}/{type}")
	public Result<List<AuthPageVO>> authPageList(@PathVariable("cgformId") String cgformId,@PathVariable("type")Integer type){
		Result<List<AuthPageVO>> result = new Result<>();
		List<AuthPageVO> authList = this.onlAuthPageService.queryAuthByFormId(cgformId, type);
		result.setResult(authList);
		result.setSuccess(true);
		return result;
	}

	/**
	 * online 数据权限查询 有效的数据
	 * @param cgformId
	 * @return
	 */
	@GetMapping(value = "/validAuthData/{cgformId}")
	public Result<List<OnlAuthData>> authDataValidList(@PathVariable("cgformId") String cgformId){
		Result<List<OnlAuthData>> result = new Result<>();
		//查看有效的数据
		LambdaQueryWrapper<OnlAuthData> query = new LambdaQueryWrapper<OnlAuthData>()
				.eq(OnlAuthData::getCgformId, cgformId)
				.eq(OnlAuthData::getStatus, AuthConstants.VALID)
				.select(OnlAuthData::getId,OnlAuthData::getRuleName);
		List<OnlAuthData> authList = this.onlAuthDataService.list(query);
		result.setResult(authList);
		result.setSuccess(true);
		return result;
	}

	/**
	 * 根据角色找online的权限  字段/按钮/数据权限  123
	 * @param roleId 角色ID
	 * @param cgformId 表单ID
	 * @param type 123
	 * @return
	 */
	@GetMapping(value = "/roleAuth")
	public Result<List<OnlAuthRelation>> roleAuthList(@RequestParam("roleId") String roleId,@RequestParam("cgformId") String cgformId,@RequestParam("type")Integer type,@RequestParam("authMode")String authMode){
		Result<List<OnlAuthRelation>> result = new Result<>();
		LambdaQueryWrapper<OnlAuthRelation> query = new LambdaQueryWrapper<OnlAuthRelation>()
				.eq(OnlAuthRelation::getRoleId,roleId)
				.eq(OnlAuthRelation::getCgformId,cgformId)
				.eq(OnlAuthRelation::getType,type)
				.eq(OnlAuthRelation::getAuthMode,authMode)
				.select(OnlAuthRelation::getAuthId);
		List<OnlAuthRelation> authList = this.onlAuthRelationService.list(query);
		result.setResult(authList);
		result.setSuccess(true);
		return result;
	}


	/* ---------------------------------------字段权限设定-begin-------------------------------------- */
	@PostMapping(value = "/roleColumnAuth/{roleId}/{cgformId}")
	@CacheEvict(value = {CacheConstant.ONLINE_LIST, CacheConstant.ONLINE_FORM}, allEntries = true, beforeInvocation=true)
	public Result<?> roleColumnAuthSave(@PathVariable("roleId")String roleId, @PathVariable("cgformId") String cgformId, @RequestBody JSONObject jsonObject){
		Result<?> result = new Result<>();
		JSONArray array = jsonObject.getJSONArray("authId");
		String authMode = jsonObject.getString("authMode");
		List<String> authIds = array.toJavaList(String.class);
		this.onlAuthRelationService.saveRoleAuth(roleId,cgformId,1, authMode, authIds);
		result.setSuccess(true);
		return result;
	}
	/* ---------------------------------------字段权限设定-end-------------------------------------- */

	/* ---------------------------------------按钮权限设定-begin-------------------------------------- */
	@PostMapping(value = "/roleButtonAuth/{roleId}/{cgformId}")
	@CacheEvict(value = {CacheConstant.ONLINE_LIST, CacheConstant.ONLINE_FORM}, allEntries = true, beforeInvocation=true)
	public Result<?> roleButtonAuthSave(@PathVariable("roleId")String roleId, @PathVariable("cgformId") String cgformId, @RequestBody JSONObject jsonObject){
		Result<?> result = new Result<>();
		JSONArray array = jsonObject.getJSONArray("authId");
		String authMode = jsonObject.getString("authMode");
		List<String> authIds = array.toJavaList(String.class);
		this.onlAuthRelationService.saveRoleAuth(roleId,cgformId,2, authMode, authIds);
		result.setSuccess(true);
		return result;
	}
	/* ---------------------------------------按钮权限设定-end-------------------------------------- */


	/* ---------------------------------------数据权限设定-begin-------------------------------------- */
	@PostMapping(value = "/roleDataAuth/{roleId}/{cgformId}")
	@CacheEvict(value = {CacheConstant.ONLINE_LIST, CacheConstant.ONLINE_FORM}, allEntries = true, beforeInvocation=true)
	public Result<?> roleDataAuthSave(@PathVariable("roleId")String roleId, @PathVariable("cgformId") String cgformId, @RequestBody JSONObject jsonObject){
		Result<?> result = new Result<>();
		JSONArray array = jsonObject.getJSONArray("authId");
		String authMode = jsonObject.getString("authMode");
		List<String> authIds = array.toJavaList(String.class);
		this.onlAuthRelationService.saveRoleAuth(roleId,cgformId,3, authMode, authIds);
		result.setSuccess(true);
		return result;
	}
	/* ---------------------------------------数据权限设定-end-------------------------------------- */

	/* ---------------------------------------流程中获取online字段-begin-------------------------------------- */
	@GetMapping(value = "/getAuthColumn/{desformCode}")
	public Result<List<AuthColumnVO>> getAuthColumnList(@PathVariable("desformCode") String desformCode) {
		//根据表信息
		OnlCgformHead head = onlCgformHeadService.getOne(new LambdaQueryWrapper<OnlCgformHead>().eq(OnlCgformHead::getTableName,desformCode));
		if(head == null ){
			Result.error("未找到对应字段信息!");
		}
		//查询表字段
		Result<List<AuthColumnVO>> result = new Result<>();
		LambdaQueryWrapper<OnlCgformField> query = new LambdaQueryWrapper<OnlCgformField>();
		query.eq(OnlCgformField::getCgformHeadId,head.getId());
		query.orderByAsc(OnlCgformField::getOrderNum);
		List<OnlCgformField> fieldList = this.onlCgformFieldService.list(query);
		if(fieldList==null || fieldList.size()==0) {
			Result.error("未找到对应字段信息!");
		}
		List<AuthColumnVO> ls = new ArrayList<>();
		for(OnlCgformField field: fieldList){
			AuthColumnVO vo = new AuthColumnVO(field);
			vo.setTableName(head.getTableName());
			vo.setTableNameTxt(head.getTableTxt());
			ls.add(vo);
		}

		//查询是否有子表
		if(oConvertUtils.isNotEmpty(head.getSubTableStr())){
			for (String tbname : head.getSubTableStr().split(",")) {
				OnlCgformHead subTable = onlCgformHeadService.getOne(new LambdaQueryWrapper<OnlCgformHead>().eq(OnlCgformHead::getTableName,tbname));
				if (subTable == null) {
					continue;
				}
				LambdaQueryWrapper subFieldQuery = new LambdaQueryWrapper<OnlCgformField>().eq(OnlCgformField::getCgformHeadId, subTable.getId());
				List<OnlCgformField> subFieldList = this.onlCgformFieldService.list(subFieldQuery);
				if(subFieldList != null ){
					for(OnlCgformField field: subFieldList){
						AuthColumnVO vo = new AuthColumnVO(field);
						vo.setTableName(subTable.getTableName());
						vo.setTableNameTxt(subTable.getTableTxt());
						ls.add(vo);
					}
				}
			}
		}
		result.setResult(ls);
		result.ok("加载字段权限数据完成");
		return result;
	}
	/* ---------------------------------------流程中获取online全选-end-------------------------------------- */

}
